package com.huadragon.marathonweb.controller.manage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.huadragon.marathoncore.security.AES;
import com.huadragon.marathoncore.security.MD5Util;
import com.huadragon.marathoncore.util.CookieUtils;
import com.huadragon.marathoncore.util.JsonUtil;
import com.huadragon.marathoncore.util.ParseHelper;
import com.huadragon.marathoncore.util.PropertyUtils;
import com.huadragon.marathonentity.common.page.PagerModel;
import com.huadragon.marathonentity.servicedomain.AccountAuthDomain;
import com.huadragon.marathonentity.servicedomain.AccountInfoDomain;
import com.huadragon.marathonentity.servicedomain.MenuInfoDomain;
import com.huadragon.marathonentity.servicedomain.RoleInfoDomain;
import com.huadragon.marathonentity.servicedomain.SimpleUserInfoDomain;
import com.huadragon.marathonservice.common.RedisService;
import com.huadragon.marathonservice.service.inter.IAccountAuthService;
import com.huadragon.marathonservice.service.inter.IAccountInfoService;
import com.huadragon.marathonservice.service.inter.IMenuInfoService;
import com.huadragon.marathonservice.service.inter.IRoleInfoService;
import com.huadragon.marathonweb.common.LoginHelper;
import com.huadragon.marathonweb.common.LoginUtil;
import com.huadragon.marathonweb.common.MenuHelper;
import com.huadragon.marathonweb.common.UserContext;

@Controller
@RequestMapping("account")
public class AccountController {

	@Autowired
	private RedisService redisService;
	@Autowired
	private IAccountInfoService accountInfoService;

	@Autowired
	private IRoleInfoService roleInfoService;

	@Autowired
	private IMenuInfoService menuInfoService;

	@Autowired
	private IAccountAuthService accountAuthService;
	
	@RequestMapping("new")
	public ModelAndView newArticle(Long id) {
		ModelAndView view = new ModelAndView("adminView");
		view.addObject("subtitle", "文章管理");
		view.addObject("currenttitle", "新建文章");
		view.addObject("viewPath", "account/new");
		return view;
	}
	
	@RequestMapping("list")
	public ModelAndView list() {
		ModelAndView view = new ModelAndView("adminView");
		view.addObject("subtitle", "用户设置");
		view.addObject("currenttitle", "用户管理");
		view.addObject("viewPath", "account/list");
		RoleInfoDomain roleInfo = new RoleInfoDomain();
		List<RoleInfoDomain> roleList = roleInfoService.selectList(roleInfo);
		view.addObject("roleList", roleList);
		return view;
	}

	@RequestMapping("listdo")
	public ModelAndView list(AccountInfoDomain req) {
		ModelAndView view = new ModelAndView("/manage/account/listdo");
		PagerModel pagerModel = accountInfoService.selectPageList(req);
		view.addObject("PagerModel", pagerModel);
		return view;
	}

	@RequestMapping("updateaccountinfo")
	@ResponseBody
	public int updateAccountInfo(HttpServletRequest request, AccountInfoDomain account) {
		if (account.getPassword() != null && !account.getPassword().isEmpty()) {
			String password = MD5Util.MD5(account.getPassword());
			account.setPassword(password);
		}
		account.setIsLoginOperate(false);
		int i = accountInfoService.update(account);
		return i;
	}

	@RequestMapping("code")
	public ModelAndView code(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("/manage/account/code");
		return mv;
	}

	@RequestMapping("logon")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("/manage/account/login");
		return mv;
	}

	@RequestMapping("getaccountinfo")
	@ResponseBody
	public AccountInfoDomain getAccountInfo(HttpServletRequest request, int accountInfoId) {
		AccountInfoDomain accountInfoDomain = new AccountInfoDomain();
		accountInfoDomain.setAccountInfoId(accountInfoId);
		return accountInfoService.selectOne(accountInfoDomain);
	}

	@RequestMapping("addaccountinfo")
	@ResponseBody
	public int addAccountInfo(HttpServletRequest request, AccountInfoDomain account) {
		if (account == null || account.getLoginName() == null || account.getLoginName().isEmpty()
				|| account.getUserName() == null || account.getUserName().isEmpty()) {
			return -1;
		}
		account.setAccountType(0);
		account.setRoleId(0);
		String password = MD5Util.MD5(account.getPassword());
		account.setPassword(password);
		return accountInfoService.insert(account);
	}

	@RequestMapping(value = "authlist", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String getAuthList(int userID) {
		List<MenuInfoDomain> menuList = menuInfoService.getMenuResourceByUserID(userID);
		return MenuHelper.getAuthJson(menuList);
	}

	@RequestMapping("updateroleid")
	@ResponseBody
	public int updateRoleID(int userID, int newRoleID) {
		AccountInfoDomain acc = new AccountInfoDomain();
		acc.setAccountInfoId(userID);
		acc.setRoleId(newRoleID);
		return accountInfoService.updateRoleID(acc);
	}

	@RequestMapping("saveauth")
	@ResponseBody
	public String saveauth(HttpServletRequest request, int userID, String newAuth, String oldAuth) {
		List<String> newList = new ArrayList<>();
		List<String> oldList = new ArrayList<>();
		List<String> diffList = new ArrayList<>();
		if (newAuth != null && !newAuth.isEmpty()) {
			Collections.addAll(newList, newAuth.split(","));
			Collections.addAll(diffList, newAuth.split(","));
		}
		if (oldAuth != null && !oldAuth.isEmpty()) {
			Collections.addAll(oldList, oldAuth.split(","));
		}

		diffList.removeAll(oldList);// diffList中剩余的是新增的权限id
		oldList.removeAll(newList);// oldList中剩余的是被删掉的权限id
		diffList.addAll(oldList);// diffList中剩余的是发生了变更的权限id
		if (diffList.size() == 0) {
			return "没有任何修改，不需要保存";
		}
		List<AccountAuthDomain> authList = new ArrayList<>();
		UserContext context = UserContext.getCurrentContext(request);
		for (String authid : diffList) {
			AccountAuthDomain authset = new AccountAuthDomain();
			authset.setAccoutId(userID);
			authset.setOptName(context.getUserName());
			authset.setMenuId(Integer.parseInt(authid));
			authList.add(authset);
		}
		accountAuthService.modifyAuthList(authList);

		return "";
	}

	@RequestMapping(value = "login", method = { RequestMethod.POST })
	public void login(HttpServletRequest request, HttpServletResponse response, @RequestParam String loginName,
			@RequestParam String password, @RequestParam String code, Integer rememberMe)
					throws ServletException, IOException {
		String basePath = PropertyUtils.getProperty("java.renrenadmin.url");
		Date loginTime = new Date();
		String sessionCode = LoginHelper.getAuthCode(request, LoginUtil.ADMIN_JSESSIONID);
		// 一次性验证码,防止暴力破解
		LoginHelper.removeAuthCodeCookie(request, response, LoginUtil.ADMIN_JSESSIONID);
		// 如果已登录,直接返回
		boolean isLogin = LoginUtil.checkIsLogin(request, response);
		// 如果已登录,直接返回已登录
		if (isLogin) {
			response.sendRedirect( "/account/index");
			return;
		}

		String error = "";
		AccountInfoDomain account = null;
		// 验证码不正确
		if (sessionCode == null || !sessionCode.toString().toLowerCase().equals(code.toLowerCase())) {
			error = "验证码不正确";
		} else {
			AccountInfoDomain accountInfo = new AccountInfoDomain();
			accountInfo.setPassword(MD5Util.MD5(password));
			accountInfo.setLoginName(loginName);
			account = accountInfoService.selectOne(accountInfo);
			if (account == null) {
				error = "用户名或密码错误";
			} else if (account.getStatus() != 1) {
				error = "您的账号已经被禁用,请联系管理员";
			}
		}
		if (!error.equals("")) {
			request.setAttribute("error", error);
			request.getServletContext().getRequestDispatcher("/account/logon").forward(request, response);
			return;
		}
		// 登录成功,写cookie
		int cookieMaxAge = -1;
		// 选择记住我,默认cookie24小时,否则随浏览器的关闭而失效
		boolean isRemeberMe = rememberMe != null && rememberMe.equals(1);
		if (isRemeberMe) {
			cookieMaxAge = 7 * 60 * 60 * 24;
		}
		account.setPassword(password);// 这个是为了给cookie准备的参数
		error = "成功";

		SimpleUserInfoDomain loginUser = new SimpleUserInfoDomain();
		loginUser.setAccountType(ParseHelper.ToInt(account.getAccountType(), 1));
		loginUser.setId(account.getAccountInfoId());
		loginUser.setLoginName(account.getLoginName());
		loginUser.setPassword("");
		loginUser.setRoleId(account.getRoleId());
		loginUser.setUserName(account.getUserName());
		String encyCookie = AES.aesEncrypt(JsonUtil.obj2string(loginUser));
		CookieUtils.setCookie(request, response, LoginUtil.LOGIN_COOKIE_NAME, encyCookie, cookieMaxAge, true);
		response.sendRedirect( "/account/index.do");
	}

}
